lib.use(['element', 'table', 'form','laydate','tablePlug','load'], function () {
    var table = layui.table;
    var layer = layui.layer;
    var form = layui.form;
    var load=layui.load;
    var tablePlug = layui.tablePlug;
    var laydate=layui.laydate;
    var searchFrm = layui.Form('searchFrm');
    var deptTable;
    var zTreeObj;
    //初始表格基础参数
    table.set(common.layui.table.config(tablePlug));

    searchFrm.selectRender();

    // 渲染表格
    deptTable = table.render({
            elem: '#deptTable'
            , url: common.util.createUrl('/sys/dept/list')
            ,where: {deptId:0}
            , cols: [[
                 {type:'checkbox'}
                , {type: 'numbers', title: '编号' }
                , { title: '名称', field: 'name' }
                , { title: '类型', field: 'type' ,templet: function (row) {return row.type==1?"人员":"机构"}}
                , {field: 'email', title: '邮箱', minwidth: 150}
                , {field: 'mobile', title: '手机', minwidth: 150}
                , { title: '是否有效', field: 'status' ,templet: function (row) {return common.dist.getValue("comm.ValidEnum",row.status);}}
                , {field: 'updateUserName', title: '更新人', width: 160}
                , {field: 'updateTime', title: '更新时间', width: 160}

            ]]
    });

    //下拉菜单
    $(".downpanel").on("click",".layui-select-title",function(e){
        $(".layui-form-select").not($(this).parents(".layui-form-select")).removeClass("layui-form-selected");
        $(this).parents(".layui-form-select").toggleClass("layui-form-selected");
        e.stopPropagation();
    });

    load.config({
         ztree: common.constant.getZtreeConfig(),
        'ztree.exhide': common.constant.getZtreeExhideConfig()
    });
    // ztree.exhide依赖了ztree所以只要load进来ztree.exhide就可以用ztree的基础功能了
    load(['ztree.exhide'], function () {
        // 配置
        var setting = {
            view: {
                selectedMulti: false
            },
            async: { // 属性配置
                enable: true,
                url:common.util.createUrl("/sys/dept/listRef"),
                autoParam:["id"],
                type: 'get',
                dataFilter: filter
            },data : {
                simpleData : {
                    enable : true,//是否采用简单数据模式
                    idKey : "id",//树节点ID名称
                    pIdKey : "parentId",//父节点ID名称
                    rootPId : -1,//根节点ID
                },
                key: {
                    name: "deptName",
                }
            },
            callback: { // 回调函数配置
                beforeAsync: beforeAsync,
                onClick: zTreeOnClickFun
            }
        };
        // 数据处理回调函数
        function filter(treeId, parentNode, r) {
            var childNodes=r.data;
            if (!childNodes) return null;
            for (var i=0, l=childNodes.length; i<l; i++) {
                childNodes[i].deptName = childNodes[i].deptName.replace(/\.n/g, '.');
            }
            return childNodes;
        }
        function beforeClick(treeId, treeNode) { // 选中节点
             return true;
        }
        function beforeAsync(treeId, treeNode) {
            return true;
        }
        function zTreeOnClickFun(){
            searchTable();
        }
        //初始第一层节点
        common.ajax.get('/sys/dept/listRef', {}, function (resp) {
            var zNodes =[{ id:0, parentId:-1, deptName:"全部", parent: true, open:true}];
            zTreeObj=$.fn.zTree.init($("#deptTree"), setting,zNodes.concat(resp.data));
       })
    })


    /**
     * 监听行单击事件，进入编辑事件
     */
    table.on('rowDouble(deptTableFilter)', function(obj){
        update(obj)
    });
    /**
     * 删除
     */
    $(document).on('click','#del',function(){
        del(table.checkStatus('deptTable'))
    });

    /**
     * 新增
     */
    $(document).on('click','#addDept',function(){
        var selectedNodes = zTreeObj.getSelectedNodes();
        var pid=0;
        if(selectedNodes&&selectedNodes.length>0){
            pid=selectedNodes[0].id;
        }
        var config={
            title:"新增机构",
            content:'sys/dept/deptForm.html?pid='+pid //iframe的url，no代表不显示滚动条
        }
        common.util.openWindow(busCommon.baseWindowConfig(config))
    });

    /**
     * 新增
     */
    $(document).on('click','#addUser',function(){
        var selectedNodes = zTreeObj.getSelectedNodes();
        var pid=0;
        if(selectedNodes&&selectedNodes.length>0){
            pid=selectedNodes[0].id;
        }
        var config={
            title:"新增用户",
            content:'sys/user/userForm.html?pid='+pid //iframe的url，no代表不显示滚动条
        }
        common.util.openWindow(busCommon.baseWindowConfig(config))
    });

    /**
     * 监听搜索条件提交事件
     */
    form.on('submit(searchFilter)', function(data){
        var param = data.field;
        searchTable(param)
        return false;
    });

    /**
     * 查询表格
     * @param params
     */
    function searchTable(params) {
        var nodes = zTreeObj.getSelectedNodes();
        params=params||{}
        params.deptId=nodes[0].id;
        params=$.extend(common.from.serializeObject('#searchFrm'),params);
        deptTable.reload({where: params})
    }
    /**
     * 刷新当前节点
     */
    function refreshNode() {
         var nodes = zTreeObj.getSelectedNodes();
        /*强行异步加载父节点的子节点。[setting.async.enable = true 时有效]*/
        zTreeObj.reAsyncChildNodes(nodes[0], 'refresh', false);
    }
    /**
     * 修改
     * @param obj
     */
    function update(obj) {
        if(!common.auth.hasPermission("sys:dept:update")){return;}
        var postData = [];
        if(obj.data.constructor === Array){
            postData=obj.data.map(function (item) {
                return item;
            });
        }else{
            postData=[obj.data]
        }
        if(postData.length!=1){common.util.error('请选择一条记录');return;}
        var config={};
        if(postData[0].type==2){
            config = {
            title:"修改机构",
            content: 'sys/dept/deptForm.html?id=' + postData[0].id, //iframe的url，no代表不显示滚动条
            }
        }else{
            config = {
                title:"修改用户",
                content: 'sys/user/userForm.html?id=' + postData[0].id, //iframe的url，no代表不显示滚动条
            }
        }
        common.util.openWindow(busCommon.baseWindowConfig(config))
    }
    /**
     * 删除
     * @param obj
     */
    function del(obj) {
        if(!common.auth.hasPermission("sys:dept:delete")){return;}
        var postData = [];
        if(obj.data.constructor === Array){
            postData=obj.data.map(function (item) {
                return item;
            });
        }else{
            postData=[obj.data]
        }
        if(postData.length!=1){common.util.error('请选择一条记录');return;}
        layer.confirm('确认删除!', function(index){
               var url='';
               if(postData.type==1){
                    url='/sys/user/delete/'+postData["id"];
               }else{
                   url='/sys/dept/delete/'+postData["id"];
               }
                common.ajax.get(url, postData, function (resp) {
                    searchTable();
                    layer.close(index);
                })
         });
    }

    window.formCallBack=function (params) {
        refreshNode();
        searchTable(params);
    };
});
